package sky.cin.framework.network.nio;

import sky.cin.framework.log.Croog;
import sky.cin.framework.network.dto.HttpServletRequest;
import sky.cin.framework.network.dto.HttpServletResponse;
import sky.cin.framework.network.dto.Servlet;
import sky.cin.framework.network.filter.Filter;
import sky.cin.framework.nio.NioEventLoop;

import java.util.Map;

public class NioServer {

    private Croog log;

    private int port;

    private static Map<String, Servlet> servletMap;


    public NioServer(Map<String, Servlet> servletMap) {
        this(servletMap, 8080);
    }

    public NioServer(Map<String, Servlet> servletMap, Integer port) {
        NioServer.servletMap = servletMap;
        this.log = new Croog("sky.cin.framework.network.nio.NioServer");
        this.port = port;
    }

    public void run() {
        new NioEventLoop(port, (channel, msg) -> {
            HttpServletRequest request = new HttpServletRequest(msg);
            HttpServletResponse response = new HttpServletResponse();
            if (!Filter.start(request, response)) {
                return null;
            }
            String requestUrl = request.getPath();
            Map<String, Servlet> servletMap = NioServer.servletMap;
            Servlet servlet = servletMap.computeIfAbsent(requestUrl, k -> servletMap.get("*"));
            servlet.doGet(request, response);
            return response.toString();
        });
        log.info(String.format("服务器正在 http://localhost:%d 上运行", port));
    }
}
